package com.lucien.framework.websocket;

import com.lucien.framework.shiro.domain.JwtToken;
import com.lucien.system.domain.ChatMessage;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionConnectedEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

import javax.websocket.Session;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class WebSocketEventListener {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 存放所有在线的客户端
     */
    private static Map<String, Session> clients = new ConcurrentHashMap<>();

    /**
     * 连接成功事件
     *
     * @param event
     */
    @EventListener
    public void handleWebSocketConnectListener(SessionConnectedEvent event) {
        MessageHeaders headers = event.getMessage().getHeaders();
        UserPrincipal userPrincipal = (UserPrincipal) headers.get("simpUser");
        String token = userPrincipal.getName();
        JwtToken jwtToken = new JwtToken(token);
        System.out.println("rabbitmq发送上线消息" + jwtToken.getPrincipal());
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setFromId(25);
        chatMessage.setFromName("system");
        chatMessage.setToId(23);
        chatMessage.setToName(String.valueOf(jwtToken.getPrincipal()));
        chatMessage.setMessageTypeId(1);
        chatMessage.setCreateTime(new Date());
        chatMessage.setContent("您的好友"+jwtToken.getPrincipal()+"已上线");
//        rabbitTemplate.convertAndSend(RabbitCons.TOPIC_EXCHANGE, RabbitCons.TOPIC_ROUTING_KEY, JSONObject.toJSONString(chatMessage));
    }

    /**
     * 用户下线消息
     * @param event
     */
    @EventListener
    public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
        UserPrincipal userPrincipal = (UserPrincipal) headerAccessor.getHeader("simpUser");
        String token = userPrincipal.getName();
        JwtToken jwtToken = new JwtToken(token);
        System.out.println("rabbitmq发送下线消息：" + jwtToken.getPrincipal());
    }

}
